import $config from '@/common/config.js';
import store from '@/store/index.js';
export default {
	common: {
		method: 'GET',
		header: {
			"content-type": "application/x-www-form-urlencoded"
		},
		data: {}
	},
	request(options = {}) {
		// uni.showLoading({
		// 	mask: true
		// })
		// options.url = options.url //测试地址
		// options.url = $config.webUrl + options.url
		options.method = options.method || this.common.method
		options.header = options.header || this.common.header
		// console.log(options.url);
		// 验证权限token
		// console.log("store.state.hasLogin===>>>", store.state.token)
		if (store.state.hasLogin) {
			options.header['X-Access-Token'] = store.state.token
		}

		return new Promise((res, rej) => {
			uni.request({
				...options,
				success: (result) => {
					// console.log(result);
					// 请求服务端失败
					if (result.statusCode !== 200) {
						uni.showToast({
							title: result.data.info || '请求失败',
							icon: 'none'
						});
						// uni.hideLoading()
						return rej(result.data)
					}
					// 成功
					// uni.hideLoading()
					if (result.data.code == 401) {
						store.commit('logout');
						uni.$emit('loginin');
					}
					res(result.data)
					// console.log(result.data);
				},
				fail: (error) => {
					uni.showToast({
						title: error.errMsg || '请求失败',
						icon: 'none'
					});
					// uni.hideLoading()
					return rej()
				}
			});
		})
	},
	get(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	post(url, data = {}, options = {}) {
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	postRaw(url, header = {}, rawData = {}, options = {}) {
		options.url = url
		options.header = header
		options.data = rawData
		options.method = 'POST'
		return this.request(options)
	},
}
